/**
 * Created by Administrator on 2014/12/10.
 */
var fs = require('fs');
var path = require('path');
var config = require('./config.json');
var LogItem = require('./lib/logItem');
var LOG_ITEM = /\{[^\{]*\}/g;
var logCache = {};

function analyseLogs() {
    var files = config.fileNames;
    files.forEach(function (file) {
        analyseLogFile(file);
    });
}

function analyseLogFile(fileName) {
    var sourceFile = path.join('./src/', fileName);
    var destFile = path.join('./dest/', fileName);

    fs.readFile(sourceFile, 'utf-8', function (err, data) {
        if (err) {
            return;
        }
        var match = LOG_ITEM.exec(data);
        var i = 0;
        while (match) {
            i++;
            var item = new LogItem(match[0]);
            if(!config.enableExclude||!shouldItemSkipped(item)){
                pushItemToCache(item);
            }
            match = LOG_ITEM.exec(data);
        }

        var j = 0;
        for (var key in logCache) {
            logCache[key].forEach(function (item) {
                fs.appendFileSync(destFile, ++j + ':' + item.toString(), 'utf-8');
            });
        }

        fs.appendFileSync(destFile, "Total exceptions count:" + i, 'utf-8');
    });
}

function pushItemToCache(item) {
    if (logCache.hasOwnProperty(item.key)) {
        var itemExist = logCache[item.key].filter(function (it) {
            return item.compare(it);
        });
        if (itemExist.length === 0) {
            logCache[item.key].push(item);
        } else {
            itemExist[0].count++;
        }
    } else {
        logCache[item.key] = [item];
    }
}

/*
忽略错误信息中包含特定错误的字符串
 */
function shouldItemSkipped(item) {
    return config.excludes.some(function (exclu) {
        return item.message.indexOf(exclu) >= 0;
    });
}

(function () {
    analyseLogs();
})();